package cn.chencaiju.doc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class AnalyzerDoc {
	private static final String DATA_PATH="E:\\camp\\camp2018";
	private static final String INDEX_PATH="E:\\camp\\camp\\lucene-code\\day01\\index";
	
	public static void main(String[] args){
		
		List<File> files = findDocxFiles(DATA_PATH);
		createIndexWriter(INDEX_PATH, files);
	}
	
	public static String getDocxFiles(File path) {
		XWPFWordExtractor extractor = null;
		try {
			FileInputStream is = new FileInputStream(path);
			extractor = new XWPFWordExtractor(new XWPFDocument(is));
			String result = extractor.getText();
			extractor.close();
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static boolean createIndexWriter(String indexPath,List<File> files) {
		IndexWriter indexWriter=null;
		try {
			indexWriter = new IndexWriter(
					FSDirectory.open(Paths.get(indexPath)),
					new IndexWriterConfig(new SmartChineseAnalyzer()));
			// 把原始的文档转化成Document对象（把文档的信息封装到Field属性里面去）
			for(File temp:files) {
				System.out.println(temp.toString());
				Document doc = convertToDocument(temp);
				// 使用IndexWriter把Document对象写到索引库里面
				indexWriter.addDocument(doc);
			}
			indexWriter.close();						
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	// 把原始的文档转化成Document对象
	private static Document convertToDocument(File file){
		Document doc = new Document();
		// 把文件的每一个信息封装到Field对象里面去
		// 名字、路径、大小、内容
		Field nameField = new TextField("name", file.getName(), Store.YES);
		Field pathField = new StoredField("path", file.getAbsolutePath());
		Field sizeField = new LongPoint("size", file.length());
		Field sizeStoredField = new StoredField("size", file.length());
		Field contentField;
		contentField=new TextField("content", getDocxFiles(file), Store.NO);
		doc.add(nameField);
		doc.add(pathField);
		doc.add(sizeField);
		doc.add(sizeStoredField);
		doc.add(contentField);
		return doc;
	}
	
	// 获取一文件夹下的所有docx文件
	public static List<File> findDocxFiles(String path) {
		List<File> files=new ArrayList<>();
		
		// 遍历文件（遍历目录和子目录，速度非常快）
		try {
			Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
				// 遍历到每个文件的时候，visitFile方法都会被调用
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {				
					String temp=file.toString();
					int indexOf = temp.lastIndexOf(".");
					String string = temp.substring(indexOf+1);
					if("docx".equals(string)) {
						files.add(file.toFile());					
//					System.out.println("find:"+file.toString());
					}
					return FileVisitResult.CONTINUE;
				}
			});
			

		} catch (IOException e) {
			e.printStackTrace();
		}
		return files;
	}
	
}
